<?php 

class Comments_model extends CI_Model {
    
    function __construct() {
        parent::__construct();
    }

    function getPublicComment($lessonId) {
        $collection = $this->mongo_db->db->selectCollection('comments');
        $cursor = $collection->find(array('checked'=>true, 'lesson'=>$lessonId));      
        return $cursor;
    }
    function getRawComment() {
        $collection = $this->mongo_db->db->selectCollection('comments');
        $cursor = $collection->find(array('checked'=>false));      
        return $cursor;
    }    
    function getUserComment($user) {
        $collection = $this->mongo_db->db->selectCollection('comments');
        $cursor = $collection->find(array('checked'=>true, 'user'=>$user));      
        return $cursor;
    }

    public function insertComment($str, $lsId, $par, $user)
    {
        $collection = $this->mongo_db->db->selectCollection('comments');
      	if(!$par) $par = null;

        $data = array(
            'user' => $user,
            'lesson' => $lsId,
            'content' => $str,
            'parent' => $par,
            'checked' => false,
            'time' => new MongoDate()
        );
        $insertOptions = array(
            'safe'    => true,
            'fsync'   => true,
            'timeout' => 10000
        );
        try {
            $result = $collection->insert($data);
            return 'success';
        }
        catch(MongoCursorException $mce) {
            return 'fail';
        }
    }   
    public function deleteCmt($id)
    {
        $collection = $this->mongo_db->db->selectCollection('comments');
        try {
            $result = $collection->remove(array('_id'=> new MongoId($id)));
            return 'success';
        }
        catch(MongoCursorException $mce) {
            return 'fail';
        }
    }   
    public function checkCmt($id)
    {
        $collection = $this->mongo_db->db->selectCollection('comments');
        try {
            $result = $collection->update(array('_id'=> new MongoId($id)), array('$set' => array('checked' => true)));
            return 'success';
        }
        catch(MongoCursorException $mce) {
            return 'fail';
        }
    }   
}   